<?php

class ProfileService extends Service_Base implements ISingleton 
{
	/**
	 *
	 * @var ProfileService
	 */
	private static $_instance;
	
	/**
	 *
	 * @return ProfileService
	 */
	public static function getInstance()
	{
		if (!self::$_instance) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}	

	public function encryptSha1Password($password) {
		$filter = new Filter_Password();
		return $filter->filterBySha1($password);
	}	
	
	public function authenticate($login, $password, $remember = false)
	{
		$authAdapter = new Auth_Adapter_Basic(
			$login,
			$password
		);
		if ($remember) {
			$authAdapter->setRemember($remember);
		}
		$auth = Zend_Auth::getInstance();
		$result = $auth->authenticate($authAdapter);
		return $result->isValid();
	}
	
	public function getProfileRowByMsisdn($msisdn) 
	{
		if (!is_numeric($msisdn) || strlen($msisdn) != 10)
		{
			return null;
		}
		$profileRow = ProfilePeer::getInstance()->fetchBy(ProfilePeer::MSISDN, $msisdn);
		return $profileRow;
	}
	
	/**
	 * Saving password to profile row
	 *
	 * @param ProfileRow $row
	 * @param string $password
	 * @return boolean
	 */
	public function savePassword(ProfileRow $row, $password)
	{
		try {
			$password = $this->encryptSha1Password($password);
			$row->setPassword($password);
			$row->save();
			return true;
		} catch (Exception $e) {
			return false;
		}
	}
	
	/**
	 * Method for saving new user to db. All data must be validated before insert
	 *
	 * @param array $data
	 * @return Db_Row|null
	 */
	public function registerNewUser(array $data)
	{
		$row = ProfilePeer::getInstance()->createRow();
		$this->saveProfileFields($row, $data);
		$row->save();
		return $row;
	}

	/**
	 * Interface for saving data to profileRow
	 *
	 * @param ProfileRow $row
	 * @param array $data
	 * @return unknown
	 */
	public function saveProfileFields(ProfileRow $row, array $data)
	{
		foreach ($data as $column => $value) {
			$row->__set($column, $value);
		}
	}
	
	/**
	 * Generating random numeric pass
	 *
	 * @return string
	 */
	public function generateRandomPassword()
	{
		return strval(rand(10, 99) . rand(10, 99) . rand(10, 99) . rand(10, 99));
	}
	
	
	/**
	 *
	 * @param string $email
	 * @return Db_Row|null
	 */
	public function getProfileRowByEmail($email)
	{
		if (!$email) {
			return null;
		}
		return ProfilePeer::getInstance()->findByEmail($email)->current();
	}
	
}